/*  HostMon/msntop - A simple program to monitor hosts on android
	Copyright (C) 2009 Devendra Laulkar

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation version 2 of the License. 

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.android.msntop;


/* Referred to */
/* http://www.helloandroid.com/node/110?page=0%2C2 */
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class HostHandler extends DefaultHandler {

	private boolean completeHost;
	private String hostName = null;
	private String status = null;
	private String comment = null;
	private String optPath = null;
	 
	List<Host> hostList = new ArrayList<Host>();
	private boolean nameFlag = false, statusFlag = false, commentFlag = false, optPathFlag=false;

	
	public List<Host> getData()
	{
		return this.hostList;
	}
	
	public void startDocument() throws SAXException {
			hostList = new ArrayList<Host>();
	}

	public void endDocument() throws SAXException {
//		Log.w("HostHandler", "Added  " + hostList.size() + " hosts from xml file");
	}
	
	public void startElement(String uri, String name, String qName, Attributes attr) throws SAXException {

		if (name.trim().equals("host"))
		{
			completeHost = false;
		}
		if (name.trim().equals("name"))
		{
			nameFlag = true;
		}
		if (name.trim().equals("status"))
		{
			statusFlag = true;
		}
		if (name.trim().equals("comment"))
		{
			commentFlag = true;
		}

	}
	public void endElement(String uri, String name, String qName)
	throws SAXException {

		if (name.trim().equals("host"))
			completeHost = true;

		if(completeHost == true)
		{
			hostList.add(new Host(hostName, status, comment));
			hostName = null;
			status = null;
			completeHost = false;
		}

		if (name.trim().equals("name"))
		{
			nameFlag = false;
			
		}

		if (name.trim().equals("status"))
		{
			statusFlag = false;
			
		}
		
		if (name.trim().equals("comment"))
		{
			commentFlag = false;
			
		}
	}

	public void characters(char ch[], int start, int length)
	{
		String chars = (new String(ch).substring(start, start + length));
		
		if(chars.trim().equals(""))
			return;
		
		if(nameFlag)
		{
			hostName = chars;
		}
		else if (statusFlag)
		{
			status = chars;
		}
		else if (commentFlag)
		{
			comment = chars;
		}
	}
}
